import cv2 as cv

# 打开视频文件
cap = cv.VideoCapture("../big_buck_bunny_720p_1mb.mp4")

# 如果打开失败则退出
if not cap.isOpened():
    print("Error: Could not open video file.")
    exit()

# 获取视频参数
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv.CAP_PROP_FPS)
fourcc = cv.VideoWriter_fourcc(*'MJPG')  # 使用 Motion JPEG 编码

# 创建 VideoWriter 对象
output_file = "output.avi"
writer = cv.VideoWriter()
writer.open(output_file, fourcc, fps, (width, height))

if not writer.isOpened():
    print("Error: Could not open the video writer.")
    cap.release()
    exit()

print(f"Video Parameters:\nResolution: {width}x{height}\nFPS: {fps}")
delay = int(1000 / fps) if fps > 0 else 30

while True:
    ret, frame = cap.read()
    if not ret:
        print("End of video or cannot read the frame.")
        break

    # 将当前帧写入到输出视频文件
    writer.write(frame)

    # 显示帧
    cv.imshow("Video", frame)

    # 按键控制播放速度
    key = cv.waitKey(delay) & 0xFF
    if key == ord('q'):  # 按 'q' 键退出
        break
    elif key == ord('+'):  # 按 '+' 键加速
        delay = max(1, delay - 10)  # 最小延迟为 1ms
        print(f"Speed up: delay = {delay}ms")
    elif key == ord('-'):  # 按 '-' 键减速
        delay += 10
        print(f"Slow down: delay = {delay}ms")

# 释放资源
cap.release()
writer.release()
cv.destroyAllWindows()

print(f"Video saved to {output_file}")
